package com.ant.collect.service.impl;

import com.ant.collect.dto.DictionaryDto;
import com.ant.collect.mapper.DictionaryMapper;
import com.ant.collect.pojo.Dictionary;
import com.ant.collect.service.IDictionaryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hzd
 * @since 2025-10-23
 */
@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements IDictionaryService {

    @Override
    public Dictionary saveDictionary(DictionaryDto dto) {
        Dictionary dic=new Dictionary();
        dic.setParentId(dto.getParentId());
        dic.setDicName(dto.getDicName().trim());
        dic.setDicValue(dto.getDicValue().trim());
        dic.setDicType(dto.getDicType().trim());
        if(dto.getId()==null){
            baseMapper.insert(dic);
        }else{
            dic.setId(dto.getId());
            baseMapper.updateById(dic);
        }
        return dic;
    }

//    @Override
//    public List<Dictionary> listTree() {
//        // 1. 查询所有符合条件的字典数据（也可分页，视需求而定）
//        List<Dictionary> dicList = baseMapper.selectList(new QueryWrapper<>().eq("",)); // 自定义方法：按类型查询
//        // 2. 筛选顶级节点（parentId = 0 或 null）
//        List<Dictionary> topNodes = dicList.stream()
//                .filter(dic -> dic.getParentId() == null || dic.getParentId() == 0)
//                .collect(Collectors.toList());
//
//        // 3. 为每个顶级节点递归设置子节点
//        for (Dictionary topNode : topNodes) {
//            setChildren(topNode, dicList);
//        }
//        return topNodes;
//    }
    /**
     * 递归查询指定类型的字典树形结构
     * @param dicType 字典类型（可选，用于过滤特定类型）
     * @return 树形结构的字典列表
     */
    public List<Dictionary> listTree(String dicType) {
        // 1. 查询所有符合条件的字典数据（也可分页，视需求而定）
        List<Dictionary> dicList = baseMapper.selectList(new QueryWrapper<Dictionary>()
                .eq("dic_type",dicType)); // 自定义方法：按类型查询
        // 2. 筛选顶级节点（parentId = 0 或 null）
        List<Dictionary> topNodes = dicList.stream()
                .filter(dic -> dic.getParentId() == null || dic.getParentId() == 0)
                .collect(Collectors.toList());
        // 3. 为每个顶级节点递归设置子节点
        for (Dictionary topNode : topNodes) {
            setChildren(topNode, dicList);
        }
        return topNodes;
    }

    /**
     * 递归为节点设置子节点
     * @param parentNode 父节点
     * @param allDics 所有字典数据（避免多次查询数据库）
     */
    private void setChildren(Dictionary parentNode, List<Dictionary> allDics) {
        // 筛选当前父节点的子节点（parentId = 父节点 id）
        List<Dictionary> children = allDics.stream()
                .filter(dic -> parentNode.getId().equals(dic.getParentId()))
                .collect(Collectors.toList());

        // 若有子节点，继续递归设置子节点的子节点
        if (!children.isEmpty()) {
            parentNode.setChildren(children);
            for (Dictionary child : children) {
                setChildren(child, allDics); // 递归
            }
        }
    }

    @Autowired
    IDictionaryService dictionaryService;
    @Override
    public void test(File tempFile) {
        List<Dictionary> dataList = readExcel(tempFile);
        if(dataList.size()>0){
            dictionaryService.saveBatch(dataList);
        }
    }


    public List<Dictionary> readExcel(File file) {
        List<Dictionary> dataList = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(file);
             XSSFWorkbook workbook = new XSSFWorkbook(fis)) {
            XSSFSheet sheet = workbook.getSheetAt(0);
            // 用于存储不同层级的 code 和对应的 id 的映射
            Map<Integer, Map<String, Integer>> levelCodeIdMap = new HashMap<>();
            for (int rowIndex = 1; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                String code = getCellValue(row.getCell(0));
                String name = getCellValue(row.getCell(1));
                String parentCode = getCellValue(row.getCell(2));
                Integer level = row.getCell(3)!= null? (int) row.getCell(3).getNumericCellValue() : null;

                Integer parentId = null;
                if (level!= null && level > 1) {
                    Map<String, Integer> parentMap = levelCodeIdMap.get(level - 1);
                    if (parentMap!= null) {
                        parentId = parentMap.get(parentCode);
                    }
                }

                Dictionary dictionary = new Dictionary();
                dictionary.setParentId(parentId);
                dictionary.setDicName(name);
                dictionary.setDicValue(code);
                dictionary.setDicType("12");// 根据实际情况设置

                dataList.add(dictionary);
            }

            // 批量插入数据并获取插入后的自增主键，然后更新映射
            updateLevelCodeIdMap(dataList, levelCodeIdMap);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }

    private void updateLevelCodeIdMap(List<Dictionary> dataList, Map<Integer, Map<String, Integer>> levelCodeIdMap) {
        for (int i = 0; i < dataList.size(); i++) {
            Dictionary dictionary = dataList.get(i);
            baseMapper.insert(dictionary);
            Integer id = dictionary.getId() != null? dictionary.getId().intValue() : null;
            Integer level = getLevelFromDictionary(dictionary);
            if (level != null) {
                levelCodeIdMap.putIfAbsent(level, new HashMap<>());
                levelCodeIdMap.get(level).put(dictionary.getDicValue(), id);
            }
        }
    }

    private static Integer getLevelFromDictionary(Dictionary dictionary) {
        // 这里简单假设可以从 dicValue 中解析出 level，实际需要根据你的数据逻辑调整
        // 例如，如果 dicValue 格式是数字且代表 level，可按如下方式解析
        try {
            return Integer.parseInt(dictionary.getDicValue());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private  static String getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf((int) cell.getNumericCellValue());
            default:
                return null;
        }
    }
}
